<?php
/**
 * 获取留言集合， 包含 留言系统留言 ， 用户留言 ，快递员录音标记
 *  支持多数据源分页 排序
 *
 *  对于申通快递员 请求 淘宝留言 内部留言 需要请求留言系统接口
 *  客户留言和 录音标记留言 统一从本地库读取
 *  再统一合并
 *
 *  @author ljp 2015-11-04
*/

namespace soa\liuyan;

use artisan\cache;
use artisan\http;

class collection {

    private $_error_code;
    private $_error_msg;

    private $_resource = array();

    private $_collect_type = array(
        'branch',
        'order',
        'customer',
		'problem'
    );

    private $_collects = array();//

    private $_user;

    private $_page_num;
    private $_page_size;
    private $_count;

    private $_mark_cache_key = 'liuyan:collection_mark:%s_%s';

    public function __construct(){}

    public function set_collects($collects){
        if(in_array($collects,$this->_collect_type) && !array_search($collects,$this->_collects)){
            $this->_collects[] = $collects;
        }
    }

    public function set_user($user){
        $this->_user = $user;
    }

    private function _resource($type){
        if(!isset($this->_resource[$type])){
			switch($type){
				case 'branch':
					$this->_resource[$type] = new \soa\sto\mcg();
					break;
				case 'customer':
					$this->_resource[$type] = new \soa\liuyan\message();
					break;
				case 'problem':
					$this->_resource[$type] = new \soa\zt\problem();
					break;
			}
            /*if(in_array($type,array('branch','order'))){
                $this->_resource[$type] = new \soa\sto\mcg();
            }else{
                $this->_resource[$type] = new \soa\liuyan\message();
            }*/
        }
        return $this->_resource[$type];
    }

    private function _last_mark_reset($marks,$next_page){
        $cache_key = sprintf($this->_mark_cache_key,$this->_user['user_id'],$next_page);
        //cache::hMset($cache_key,$marks);
        //cache::expire($cache_key,3600);
        cache::set($cache_key,$marks,3600);
    }

    private function _get_mask($page){
        $cache_key = sprintf($this->_mark_cache_key,$this->_user['user_id'],$page);
        return cache::get($cache_key);
    }

    public function getList($where,$page_num = 1, $page_size = 20){

        $this->_page_num = $page_num;
        $this->_page_size = $page_size;

        $urls = array();
        $time_mark = $page_num > 1 ? $this->_get_mask($page_num) : 0;

        if($page_num > 1 && !$time_mark){
            return array(
                'count' => 0,
                'list' => array()
            );
        }

        foreach($this->_collects as $r){
			switch($r){
				case 'branch':
					$where['user_no'] = $this->_user['userno'];
					$where['courier_id'] = $this->_user['user_id'];

					if($time_mark){
						$where['start_timestramp'] = $time_mark;
					}

					if(!isset($where['exp_no']) && isset($where['user_mobile'])){//逻辑不通，不影响功能
						continue;
					}

					if(isset($where['exp_no'])) {
						$where['waybill_no'] = $where['exp_no'];
					}

					$data = array_merge($where,array('p' => 1, 'pSize' => $page_size));
					break;
				case 'customer':
					if($time_mark){
						$where['start_timestramp'] = $time_mark;
					}
					if($where['poster_role'] != 'counterman'){
						$where['msg_type'] = '<>complaints'; // C 端默认显示非投诉留言内容
					}
					
					$data = array_merge($where,array('page_num' => 1, 'page_size' => $page_size));
					break;
				case 'problem':
					if($time_mark){
						$where['start_timestramp'] = $time_mark;
					}
					
					$data = array_merge($where,array('page_num' => 1, 'page_size' => $page_size));
					break;
			}

			if(in_array($r,array('customer','problem')) && isset($where['assign_status'])){//当查询assign_status时，只查申通内部留言
				continue;
			}

            $s[$r] = $where;
            $urls[$r] = $this->_resource($r)->topic_list_request($data);
        }

		//logDebug($urls,'lx920');
        $result = $result_cnt = array();
        $response_collection = http::mutiGet($urls);
        foreach($response_collection as $r => $data){
			//logDebug($r,'lx920');
            $json_data = json_decode($data,true);
            if(json_last_error() != JSON_ERROR_NONE){
                $this->setError(9999,$data);
                continue;
            }

            if(!isset($json_data['code']) || $json_data['code'] > 0){
                $this->setError($json_data['code'],$json_data['msg']);
                continue;
            }

            $result_cnt[$r] = $r == 'customer' ? (int)$json_data['data']['total_records'] : (int)$json_data['data']['count'];
            $result[$r] = $r == 'customer' ? $json_data['data']['data'] : $json_data['data']['list'];
        }

        if($this->_error_code){
            //return null;
        }

        $result_count = array_sum($result_cnt);

        $list = $time_sort_list = $last_row_mark = array();
        foreach($result as $r => $data){
            foreach($data as $row){
                $row['m_type'] = $r;
                $list[] = $row;
/*
                $d = array(
                    'm_type' => $r,
                    'updatetime' => $row['updatetime'],
                );

                $list[] = $d;
*/
            }
        }

        if(!$result_count || empty($list)){
            return array(
                'count' => 0,
                'list' => array()
            );
        }

        $sortArray = array();
        foreach ($list as $i => $r) {
            $sortArray[$i] = strtotime($r['updatetime']);
        }

        array_multisort($sortArray,SORT_DESC,$list);

        $return_list = array_slice($list,0,$this->_page_size);

        $last_row_mark = strtotime($return_list[count($return_list) -1]['updatetime']);

        $this->_last_mark_reset($last_row_mark,++$page_num);

        return array(
            'count' => array_sum($result_cnt),
            'list' => $return_list
        );
    }

    public function getUnreadCount($where){

        $urls = array();
        foreach($this->_collects as $r){
            if(in_array($r,array('branch','order'))){
                $where['user_no'] = $this->_user['userno'];
                $where['org_code'] = $this->_user['shop_code'];
                $where['courier_id'] = $this->_user['user_id'];
            }

            $urls[$r] = $this->_resource($r)->unread_count_request($where);
        }

        $result = $result_cnt = array();
        $response_collection = http::mutiGet($urls);
		if(!empty($response_collection)){
			foreach($response_collection as $r => $data){
				$json_data = json_decode($data,true);
				if(json_last_error() != JSON_ERROR_NONE){
					$this->setError(9999,$data);
					continue;
				}

				if(!isset($json_data['code']) || $json_data['code'] > 0){
					$this->setError($json_data['code'],$json_data['msg']);
					continue;
				}

				$result[$r] = (int)$json_data['data'];
			}
			if($this->_error_code){
				return null;
			}
		}
        
        return array_sum($result);
    }

    public function setError($code,$msg){
        $this->_error_code = $code;
        $this->_error_msg = $msg;
    }

    public function getCode(){
        return $this->_error_code;
    }

    public function getMsg(){
        return $this->_error_msg;
    }
}